const { PostItem, User, CommentItem } = require('../db')
// const { col } = require('sequelize');

//根据postId 分页获取评论
exports.getCommentsByPostId = async (req, res) => {
    try {
        const { postId, page = 1, pageSize = 10 } = req.query;
        const skip = (page - 1) * pageSize;

        // 查询没有 parentId 的一级评论
        const rootComments = await CommentItem.findAndCountAll({
            where: { postId, parentId: null },
            include: [
                {
                    model: User,
                    attributes: ['username', 'avatarUrl']
                }
            ],
            limit: parseInt(pageSize),
            offset: skip,
            order: [['createdAt', 'DESC']]
        });
        const totalRes = await CommentItem.count({ where: { postId } });
        // 异步计算每条评论的回复总数
        const commentsWithReplies = await Promise.all(rootComments.rows.map(async (comment) => {
            const commentId = comment.id;
            const totalReplies = await CommentItem.count({
                where: { parentId: commentId }
            });
            const commentData = comment.get({ plain: true }); // 转换为普通对象
            commentData.totalReplies = totalReplies;
            return commentData;
        }));

        res.send({
            status: 200,
            comments: commentsWithReplies, // 确保发送的是普通对象数组
            total: totalRes
        });
    } catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}
// 根据commentId获取子评论,获取回复
exports.getCommentsByCommentId = async (req, res) => {
    try {
        const { parentId, page = 1, pageSize = 5 } = req.query;
        const skip = (page - 1) * pageSize;

        // 查询指定parentId的回复
        const comments = await CommentItem.findAndCountAll({
            where: { parentId },
            include: [
                {
                    model: User,
                    attributes: ['username', 'avatarUrl']
                }
            ],
            limit: parseInt(pageSize),
            offset: skip,
            order: [['createdAt', 'DESC']] // 按创建时间降序排列
        });

        // 计算总页数
        const totalPage = Math.ceil(comments.count / parseInt(pageSize));

        res.send({
            status: 200,
            data: {
                total: comments.count, // 总回复数
                currentPage: parseInt(page), // 当前页码
                totalPage: totalPage, // 总页数
                comments: comments.rows.map(comment => comment.get({ plain: true })) // 包含回复的数组
            }
        });
    } catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

// 根据postId新建评论
exports.createComment = async (req, res) => {
    try {
        let { postId, content, parentId } = req.body
        // if (parentId) {
        //     postId = null
        // }
        const { id: UserId } = req.user
        const comment = await CommentItem.create({
            postId,
            content,
            UserId,
            parentId,
            date: new Date().toISOString().slice(0, 10).replace(/-/g, '年').replace(/-/g, '月') + '日',
        })

        // 更新对应帖子的评论数
        await PostItem.increment('commentNums', {
            by: 1, // 增加的数量
            where: {
                id: postId // 根据postId来更新
            }
        });

        res.send({
            status: 200,
            comment
        })
    }
    catch (error) {
        console.error(error);
        res.status(500).send('内部服务器错误');
    }
}

//删除自己的评论
exports.deleteComment = async (req, res) => {
    try {
        const { id: userId } = req.user
        console.log(userId, 'userId');

        const userInf = await User.findOne({
            where: { id: userId },
        })
        console.log(userInf, 'userInf');
        const { commentId } = req.body
        const comment = await CommentItem.findByPk(commentId)
        const canDelete = comment.UserId === userId || userInf.role === 'jyu_admin'
        console.log(canDelete, 'canDelete');
        if (!comment) {
            res.status(404).send('评论不存在')
        }
        else if (canDelete) {
            await comment.destroy()
            res.send({
                status: 200,
                message: '删除成功'
            })
        }
        else {
            res.status(403).send('无权限删除')
        }
    } catch (err) {
        console.log(err);

        res.status(500).send('服务器错误')
    }
}